package com.datang.pet.api.talkController;


import com.datang.pet.common.mergeUtils.MergeVideoMp3;
import com.datang.pet.common.ossUtils.OssUtil;
import com.datang.pet.common.ossUtils.UploadFile;
import com.datang.pet.common.properties.MergeAttr;
import com.datang.pet.common.utils.StringUtils;
import com.datang.pet.pojo.Resource;
import com.datang.pet.service.TalkService;
import com.datang.pet.vo.AddTalkRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;

@Component
public class MergeConsumer {

    @Autowired
    private UploadFile uploadFile;

    @Autowired
    private TalkService talkService;

    @JmsListener(destination = "Mp4MergeMp3")
    public void receiveQueue(AddTalkRequest addTalkRequest) throws Exception {
        //拿到视频
        Resource resource = addTalkRequest.getResourceList().get(0);

        //视频
        String videoInput = OssUtil.getBucketUrl(2) + resource.getSrc();
        //音频
        String audioInput = addTalkRequest.getBgmSrc();
        //时长
        Double time = resource.getSize();
        //输出名称
        String output = StringUtils.getSourceName(resource.getSrc());

        try {
            MergeVideoMp3.convertor(videoInput, audioInput, time, output);
        } catch (Exception e) {
            throw new Exception("音频视频合成出错了");
        }

        //视频文件流
        File temporaryPath = new File(MergeAttr.TEMPORARYPath + output);

        //此处 拿到合成好临时存放的文件流
        FileInputStream inputStream = new FileInputStream(temporaryPath);

        //此处执行上传文件到 oss 需要注意的是这里的文件名要和js前端文件名一致.这样就可以直接覆盖oss文件
        uploadFile.uploadFile(inputStream, output, 2);

        //关闭流
        inputStream.close();

        //删除临时视频
        temporaryPath.delete();

        //添加喵文
        talkService.addTalk(addTalkRequest);

    }
}
